package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.service.ISysUserPostService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * @Classname SysUserPostServiceImpl
 * @Description 用户与岗位关联表 业务层处理
 * @Date 2025/10/28 09:57
 * @Created by 陈九常
 */
@Service
public class SysUserPostServiceImpl extends ServiceImpl<SysUserPostMapper, SysUserPost> implements ISysUserPostService {

    /**
     * 根据用户ID删除用户岗位关联
     * 对应XML: deleteUserPostByUserId
     */
    @Override
    public int deleteUserPostByUserId(Long userId) {
        LambdaQueryWrapper<SysUserPost> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserPost::getUserId, userId);
        return baseMapper.delete(wrapper);
    }

    /**
     * 统计岗位下的用户数量
     * 对应XML: countUserPostById
     */
    @Override
    public int countUserPostById(Long postId) {
        LambdaQueryWrapper<SysUserPost> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserPost::getPostId, postId);
        return Math.toIntExact(baseMapper.selectCount(wrapper));
    }

    /**
     * 批量删除用户岗位关联
     * 对应XML: deleteUserPost
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserPost(Long[] userIds) {
        if (userIds == null || userIds.length == 0) {
            return 0;
        }

        LambdaQueryWrapper<SysUserPost> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SysUserPost::getUserId, Arrays.asList(userIds));
        return baseMapper.delete(wrapper);
    }

    /**
     * 批量插入用户岗位关联
     * 对应XML: batchUserPost
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchUserPost(List<SysUserPost> userPostList) {
        if (userPostList == null || userPostList.isEmpty()) {
            return 0;
        }
        // 使用saveBatch方法进行批量插入，成功返回插入的记录数，失败返回0
        return saveBatch(userPostList) ? userPostList.size() : 0;
    }
}
